#include <SDL/SDL.h>

#include "common.hh"
#include "tbb/task_scheduler_init.h"
#include "tbb/parallel_for.h"
#include "tbb/blocked_range2d.h"

tbb::spin_mutex global_screen_mutex;

class Draw
{
  SDL_Surface	*affichage;
  Uint32	img[HEIGHT][WIDTH];

 public:
  Draw (SDL_Surface	*affichage_,
	  Uint32	**img_)
    : affichage(affichage_)
    {
      for (unsigned i = 0; i < HEIGHT; ++i)
	for (unsigned j = 0; j < WIDTH; ++j)
	  img[i][j] = img_[i][j];
    }

  void operator() (const tbb::blocked_range2d<int>& r) const
  {
    for (int i = r.rows().begin(); i!= r.rows().end(); ++i)
      {
	for (int j = r.cols().begin(); j!= r.cols().end(); ++j)
	  {
	    setPixel (affichage, j, i, img[i][j]);
	  }
      }

  }
};

void setPixel(SDL_Surface	*affichage,
	      unsigned		x,
	      unsigned		y,
	      Uint32		coul)
{
  *((Uint32*)(affichage->pixels) + x + y * affichage->w) = coul;
}

void draw(Uint32		**img,
	  SDL_Surface		*affichage)
{
  tbb::parallel_for(tbb::blocked_range2d<int>(0,HEIGHT, 0,WIDTH),
  		    Draw(affichage, img), tbb::auto_partitioner());
}
